﻿<template>
  <div class="game-canvas-container">
    <!-- 主游戏画布 -->
    <canvas
      ref="gameCanvas"
      :width="canvasWidth"
      :height="canvasHeight"
      class="game-canvas"
      tabindex="0"
      @keydown="handleKeyDown"
      @keyup="handleKeyUp"
      @blur="handleBlur"
    ></canvas>

    <!-- 游戏UI覆盖层 -->
    <div class="game-overlay">
      <!-- 路径长度警告 -->
      <div v-if="showPathWarning" class="path-warning">
        <span class="warning-icon">⚠️</span>
        <span>画线过长 ({{ Math.round(pathProgress) }}%)</span>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: pathProgress + '%' }"></div>
        </div>
      </div>

      <!-- 威胁警告 -->
      <div v-if="showThreatWarning" class="threat-warning">
        <span class="warning-icon">💥</span>
        <span>危险！敌方轨迹接近</span>
      </div>

      <!-- 道具状态 -->
      <div v-if="currentPowerUp" class="powerup-status">
        <span class="powerup-icon">{{ getPowerUpIcon(currentPowerUp.type) }}</span>
        <span class="powerup-name">{{ getPowerUpName(currentPowerUp.type) }}</span>
        <span class="powerup-time">{{ Math.ceil(currentPowerUp.timeLeft / 1000) }}s</span>
      </div>

      <!-- 控制提示 -->
      <div class="controls-hint">
        <div>WASD: 移动</div>
        <div>J: 使用道具</div>
      </div>
    </div>

    <!-- 死亡复活界面 -->
    <div v-if="isDead" class="death-overlay">
      <div class="death-modal">
        <div class="death-icon">💀</div>
        <h2 class="death-title">你死了！</h2>
        <p class="death-reason">{{ deathReason }}</p>
        <div class="respawn-countdown">
          <div class="countdown-circle">
            <svg width="80" height="80">
              <circle cx="40" cy="40" r="35" fill="none" stroke="#333" stroke-width="6"/>
              <circle cx="40" cy="40" r="35" fill="none" stroke="#fff" stroke-width="6"
                      :stroke-dasharray="220" 
                      :stroke-dashoffset="220 * (1 - respawnProgress)"
                      transform="rotate(-90 40 40)"/>
            </svg>
            <div class="countdown-number">{{ respawnTime }}</div>
          </div>
          <div class="countdown-label">秒后复活</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { lineDrawingGameService } from '@/services/lineDrawingGameService'

// Props
const props = defineProps({
  gameState: {
    type: Object,
    default: () => ({})
  },
  playerId: {
    type: String,
    required: true
  }
})

// Emits
const emit = defineEmits(['error'])

// Canvas引用和配置
const gameCanvas = ref(null)
const canvasWidth = ref(1200)
const canvasHeight = ref(800)
let ctx = null

// 游戏世界配置
const GAME_CONFIG = {
  mapRadius: 1000,
  mapCenterX: 1000,
  mapCenterY: 1000,
  safeZoneRadius: 50,
  maxPathLength: 1500,
  moveSpeed: 200
}

// 视口系统（跟随玩家）
const viewport = reactive({
  x: 0,
  y: 0,
  targetX: 0,
  targetY: 0,
  smoothness: 0.15 // 增加平滑度，让跟随更明显
})

// 玩家移动系统
const movement = reactive({
  keys: {},
  direction: { x: 0, y: 0 },
  isMoving: false,
  lastUpdate: 0,
  lastSent: 0,
  moveInterval: null
})

// 绘画系统
const drawing = reactive({
  isActive: false,
  path: [],
  length: 0,
  localTrail: []
})

// 游戏状态
const players = ref([])
const powerUps = ref([])
const currentPlayer = ref(null)

// UI状态
const showPathWarning = ref(false)
const showThreatWarning = ref(false)
const pathProgress = ref(0)
const currentPowerUp = ref(null)

// 死亡复活
const isDead = ref(false)
const deathReason = ref('')
const respawnTime = ref(0)
const respawnProgress = ref(0)
const respawnTimer = ref(null)

// 游戏循环
const gameLoop = reactive({
  animationId: null,
  lastFrame: 0
})

// 计算属性
const myPlayer = computed(() => {
  return players.value.find(p => p.PlayerId === props.playerId)
})

// 核心游戏逻辑
const updateGameState = (newState) => {
  if (!newState) return
  
  console.log('[Canvas] 游戏状态更新:', newState)
  
  // 处理CamelCase映射
  const playersData = newState.players || newState.Players || []
  const powerUpsData = newState.powerUps || newState.PowerUps || []
  
  // 更新玩家数据 - 处理每个玩家的字段映射
  players.value = playersData.map(player => ({
    ...player,
    PlayerId: player.playerId || player.PlayerId,
    Username: player.username || player.Username,
    IsAlive: player.isAlive !== undefined ? player.isAlive : player.IsAlive,
    CurrentPosition: player.currentPosition || player.CurrentPosition,
    Color: player.color || player.Color,
    Territories: player.territories || player.Territories,
    TotalTerritoryArea: player.totalTerritoryArea || player.TotalTerritoryArea,
    CurrentPath: player.currentPath || player.CurrentPath,
    IsDrawing: player.isDrawing !== undefined ? player.isDrawing : player.IsDrawing,
    IsHost: player.isHost !== undefined ? player.isHost : player.IsHost,
    MovementSpeed: player.movementSpeed || player.MovementSpeed
  }))
  
  powerUps.value = powerUpsData
  
  // 更新当前玩家
  updateCurrentPlayer()
  
  // 更新视口
  updateViewport()
  
  // 更新UI状态
  updateUIState()
}

const updateCurrentPlayer = () => {
  // 通过PlayerId查找玩家（支持CamelCase和PascalCase）
  const player = players.value.find(p => (p.PlayerId === props.playerId) || (p.playerId === props.playerId))
  
  console.log('[Canvas] 查找当前玩家:', {
    playerId: props.playerId,
    playersCount: players.value.length,
    players: players.value.map(p => ({ id: p.PlayerId || p.playerId, username: p.Username || p.username })),
    found: !!player
  })
  
  if (player) {
    const wasAlive = currentPlayer.value?.IsAlive
    const wasMoving = movement.isMoving
    const localPosition = wasMoving ? currentPlayer.value?.CurrentPosition : null
    
    currentPlayer.value = player
    
    // 如果正在移动，保持本地预测的位置，避免服务器延迟导致的抖动
    if (wasMoving && localPosition && currentPlayer.value?.CurrentPosition) {
      const serverPos = currentPlayer.value.CurrentPosition
      const localPos = localPosition
      const distance = Math.sqrt(
        Math.pow(serverPos.x - localPos.x, 2) + 
        Math.pow(serverPos.y - localPos.y, 2)
      )
      
      // 如果本地预测和服务器位置差距太大，才使用服务器位置
      if (distance > 50) {
        console.log('[Canvas] 本地预测偏差过大，使用服务器位置:', { server: serverPos, local: localPos, distance })
      } else {
        currentPlayer.value.CurrentPosition = localPos
      }
    }
    
    // 处理死亡状态变化（兼容CamelCase字段）
    const isAlive = player.IsAlive !== undefined ? player.IsAlive : player.isAlive
    
    console.log('[Canvas] 死亡状态变化检测:', {
      wasAlive,
      isAlive,
      shouldHandleDeath: wasAlive === true && !isAlive,
      shouldHandleRespawn: wasAlive === false && isAlive
    })
    
    // 只有明确的状态变化才触发处理
    // if (wasAlive === true && !isAlive) {
    //   handleDeath()
    // } else if (wasAlive === false && isAlive) {
    //   handleRespawn()
    // }
    
    // 同步绘画状态（兼容CamelCase字段）
    const isDrawing = player.IsDrawing !== undefined ? player.IsDrawing : player.isDrawing
    const currentPath = player.CurrentPath || player.currentPath
    const pathLength = player.CurrentPathLength || player.currentPathLength
    
    if (isDrawing && currentPath) {
      drawing.isActive = true
      drawing.path = [...currentPath]
      drawing.length = pathLength || 0
    } else {
      drawing.isActive = false
      drawing.path = []
      drawing.length = 0
    }
    
    // 更新死亡状态
    isDead.value = !player.IsAlive
    
    // 立即更新视角跟随当前玩家
    updateViewport()
    
    // 如果是首次找到玩家，立即设置视角到玩家位置（无平滑过渡）
    if (!viewport.targetX && !viewport.targetY && player.CurrentPosition) {
      const position = player.CurrentPosition
      const posX = position.x || position.X
      const posY = position.y || position.Y
      if (posX !== undefined && posY !== undefined) {
        viewport.x = posX - canvasWidth.value / 2
        viewport.y = posY - canvasHeight.value / 2
        viewport.targetX = viewport.x
        viewport.targetY = viewport.y
        console.log('[Viewport] 初始化视角到玩家位置:', { x: viewport.x, y: viewport.y })
      }
    }
  }
}

const updateViewport = () => {
  if (!currentPlayer.value) return
  
  // 兼容不同的字段格式
  const position = currentPlayer.value.CurrentPosition || currentPlayer.value.currentPosition
  if (!position) return
  
  const posX = position.x || position.X
  const posY = position.y || position.Y
  
  if (posX === undefined || posY === undefined) return
  
  // 计算目标视口位置（玩家居中）
  const targetX = posX - canvasWidth.value / 2
  const targetY = posY - canvasHeight.value / 2
  
  // 从游戏状态获取地图尺寸，如果不存在则使用配置
  const mapWidth = props.gameState?.mapWidth || props.gameState?.MapWidth || GAME_CONFIG.mapRadius * 2
  const mapHeight = props.gameState?.mapHeight || props.gameState?.MapHeight || GAME_CONFIG.mapRadius * 2
  
  // 限制在地图范围内
  const boundedTargetX = Math.max(0, Math.min(targetX, mapWidth - canvasWidth.value))
  const boundedTargetY = Math.max(0, Math.min(targetY, mapHeight - canvasHeight.value))
  
  // 调试信息（间歇性输出）
  if (Math.random() < 0.001) { // 1/1000 概率输出，避免日志过多
    console.log(`[Viewport] 玩家位置: (${posX}, ${posY}), 视角目标: (${boundedTargetX.toFixed(1)}, ${boundedTargetY.toFixed(1)}), 地图尺寸: ${mapWidth}x${mapHeight}`)
  }
  
  // 平滑插值避免视角跳跃  
  const lerpFactor = 0.1
  viewport.targetX += (boundedTargetX - viewport.targetX) * lerpFactor
  viewport.targetY += (boundedTargetY - viewport.targetY) * lerpFactor
}

const updateUIState = () => {
  if (!currentPlayer.value) {
    showPathWarning.value = false
    showThreatWarning.value = false
    currentPowerUp.value = null
    return
  }
  
  // 路径长度警告
  if (drawing.isActive) {
    pathProgress.value = Math.min((drawing.length / GAME_CONFIG.maxPathLength) * 100, 100)
    showPathWarning.value = pathProgress.value > 70
  } else {
    showPathWarning.value = false
  }
  
  // 威胁警告
  showThreatWarning.value = currentPlayer.value.IsUnderThreat || false
  
  // 道具状态
  updatePowerUpStatus()
}

const updatePowerUpStatus = () => {
  if (!currentPlayer.value?.CurrentPowerUp) {
    currentPowerUp.value = null
    return
  }
  
  if (currentPlayer.value.PowerUpExpireTime) {
    const expireTime = new Date(currentPlayer.value.PowerUpExpireTime)
    const timeLeft = Math.max(0, expireTime.getTime() - Date.now())
    
    if (timeLeft > 0) {
      currentPowerUp.value = {
        type: currentPlayer.value.CurrentPowerUp,
        timeLeft
      }
    } else {
      currentPowerUp.value = null
    }
  }
}

// 键盘控制
const handleKeyDown = (event) => {
  if (isDead.value) return
  
  const key = event.key.toLowerCase()
  
  // 道具使用
  if (key === 'j' && currentPlayer.value?.CurrentPowerUp) {
    usePowerUp()
    event.preventDefault()
    return
  }
  
  // 移动控制
  if (['w', 'a', 's', 'd'].includes(key)) {
    event.preventDefault()
    
    if (!movement.keys[key]) {
      movement.keys[key] = true
      updateMovement()
      
      if (!movement.isMoving) {
        startMoving()
      }
    }
  }
}

const handleKeyUp = (event) => {
  const key = event.key.toLowerCase()
  
  if (['w', 'a', 's', 'd'].includes(key)) {
    movement.keys[key] = false
    updateMovement()
    
    if (!hasActiveKeys()) {
      stopMoving()
    }
  }
}

const handleBlur = () => {
  // 失去焦点时停止所有移动
  movement.keys = {}
  stopMoving()
}

const hasActiveKeys = () => {
  return movement.keys.w || movement.keys.a || movement.keys.s || movement.keys.d
}

const updateMovement = () => {
  movement.direction = {
    x: (movement.keys.d ? 1 : 0) - (movement.keys.a ? 1 : 0),
    y: (movement.keys.s ? 1 : 0) - (movement.keys.w ? 1 : 0)
  }
  
  // 标准化方向向量
  const length = Math.sqrt(movement.direction.x ** 2 + movement.direction.y ** 2)
  if (length > 0) {
    movement.direction.x /= length
    movement.direction.y /= length
  }
}

const startMoving = () => {
  if (movement.isMoving || isDead.value) return
  
  movement.isMoving = true
  movement.lastUpdate = Date.now()
  movement.lastSent = 0 // 上次发送到后端的时间
  
  // 本地移动更新：60fps 流畅显示
  movement.moveInterval = setInterval(processMovement, 16) // ~60fps 本地预测
  
  console.log('[Canvas] 开始移动')
}

const stopMoving = () => {
  if (!movement.isMoving) return
  
  movement.isMoving = false
  
  if (movement.moveInterval) {
    clearInterval(movement.moveInterval)
    movement.moveInterval = null
  }
  
  console.log('[Canvas] 停止移动')
}

const processMovement = () => {
  if (!movement.isMoving || !currentPlayer.value?.IsAlive) return
  
  const now = Date.now()
  const deltaTime = now - movement.lastUpdate
  movement.lastUpdate = now
  
  if (movement.direction.x !== 0 || movement.direction.y !== 0) {
    const currentPos = currentPlayer.value.CurrentPosition
    if (!currentPos) return
    
    // 计算移动距离
    let speed = GAME_CONFIG.moveSpeed
    
    // 道具加成
    if (currentPlayer.value.CurrentPowerUp === 'Lightning') {
      speed *= 1.6
    }
    
    // 领地加成/减益
    if (isInOwnTerritory(currentPos)) {
      speed *= 1.15
    } else if (isInEnemyTerritory(currentPos)) {
      speed *= 0.8
    }
    
    const distance = (speed * deltaTime) / 1000
    const newX = currentPos.x + movement.direction.x * distance
    const newY = currentPos.y + movement.direction.y * distance
    
    // 边界检查
    if (isWithinMapBounds(newX, newY)) {
      // 本地预测：立即更新位置用于流畅显示
      currentPlayer.value.CurrentPosition = { x: newX, y: newY }
      
      // 处理自动绘画
      handleAutoDrawing(newX, newY)
      
      // 限制后端同步频率：最多每100ms发送一次到后端
      if (now - movement.lastSent >= 100) {
        movement.lastSent = now
        console.log('[Canvas] 发送移动到后端:', { x: newX, y: newY })
        sendMove(newX, newY)
      }
    }
  }
}

// 自动绘画逻辑
const handleAutoDrawing = (newX, newY) => {
  const newPos = { x: newX, y: newY }
  
  console.log('[Canvas] 检查自动绘画:', {
    position: newPos,
    isActive: drawing.isActive,
    isAlive: currentPlayer.value?.IsAlive,
    inSafeZone: isInSafeZone(newPos),
    inOwnTerritory: isInOwnTerritory(newPos)
  })
  
  // 检查是否应该开始绘画
  if (!drawing.isActive) {
    if (!isInSafeZone(newPos) && !isInOwnTerritory(newPos)) {
      startDrawing(newPos)
      // 不要 return，继续执行轨迹点添加逻辑
    } else {
      return // 只有在不需要开始绘画时才 return
    }
  }
  
  // 添加轨迹点到本地轨迹
  const lastPos = drawing.localTrail.length > 0 ? 
    drawing.localTrail[drawing.localTrail.length - 1] : null
  
  if (!lastPos) {
    // 如果没有上一个点，直接添加当前点
    drawing.localTrail.push(newPos)
    console.log('[Canvas] 添加第一个轨迹点:', newPos)
  } else {
    // 计算距离，如果足够远才添加新点
    const distance = Math.sqrt(
      Math.pow(newX - lastPos.x, 2) + Math.pow(newY - lastPos.y, 2)
    )
    
    if (distance >= 3) {
      drawing.localTrail.push(newPos)
      drawing.length += distance
      console.log('[Canvas] 添加新轨迹点:', newPos, '距离:', distance, '总长度:', drawing.length)
      
      // 检查是否可以闭合
      if (isInOwnTerritory(newPos) || isInSafeZone(newPos)) {
        completeDrawing(newPos)
      }
    }
  }
}

const startDrawing = (startPos) => {
  if (drawing.isActive || !currentPlayer.value?.IsAlive) {
    console.log('[Canvas] 无法开始绘画:', {
      isActive: drawing.isActive,
      isAlive: currentPlayer.value?.IsAlive,
      reason: drawing.isActive ? '已在绘画中' : '玩家未存活'
    })
    return
  }
  
  drawing.isActive = true
  drawing.localTrail = [startPos]
  drawing.length = 0
  
  console.log('[Canvas] 🎨 开始绘画:', startPos, 'localTrail长度:', drawing.localTrail.length)
}

const completeDrawing = (endPos) => {
  if (!drawing.isActive || drawing.localTrail.length < 3) return
  
  console.log('✅ 完成绘画')
  
  // 发送完成绘画指令
  sendCompleteDrawing(endPos)
  
  // 重置绘画状态
  resetDrawing()
}

const resetDrawing = () => {
  drawing.isActive = false
  drawing.localTrail = []
  drawing.length = 0
}

// 网络通信
const sendMove = async (x, y) => {
  if (!lineDrawingGameService.isConnected) return
  
  // 检查当前玩家状态
  if (!currentPlayer.value) {
    console.warn('[Canvas] 无法移动：当前玩家为空')
    return
  }
  
  const isAlive = currentPlayer.value.IsAlive !== undefined ? currentPlayer.value.IsAlive : currentPlayer.value.isAlive
  if (!isAlive) {
    console.warn('[Canvas] 无法移动：玩家已死亡', currentPlayer.value)
    return
  }
  
  console.log('[Canvas] 发送移动：', { x, y, playerId: props.playerId, playerAlive: isAlive })
  
  // 添加发送频率限制，最小间隔20ms
  const now = Date.now()
  if (movement.lastSent && (now - movement.lastSent) < 20) {
    return
  }
  movement.lastSent = now
  
  try {
    await lineDrawingGameService.playerMove(x, y)
  } catch (error) {
    console.error('[Canvas] 移动失败:', error)
    emit('error', '移动失败')
  }
}

const sendCompleteDrawing = async (endPos) => {
  if (!lineDrawingGameService.isConnected) return
  
  try {
    await lineDrawingGameService.completeDrawing(endPos.x, endPos.y)
  } catch (error) {
    console.error('[Canvas] 完成绘画失败:', error)
    emit('error', '完成绘画失败')
  }
}

const usePowerUp = async () => {
  if (!currentPlayer.value?.CurrentPowerUp || !lineDrawingGameService.isConnected) return
  
  try {
    await lineDrawingGameService.usePowerUp(currentPlayer.value.CurrentPowerUp)
    console.log('[Canvas] 使用道具:', currentPlayer.value.CurrentPowerUp)
  } catch (error) {
    console.error('[Canvas] 使用道具失败:', error)
    emit('error', '使用道具失败')
  }
}

// 死亡复活处理
const handleDeath = () => {
  console.log('[Canvas] 玩家死亡')
  isDead.value = true
  deathReason.value = currentPlayer.value?.DeathReason || '被击败'
  resetDrawing()
  stopMoving()
  startRespawnTimer()
}

const handleRespawn = () => {
  console.log('[Canvas] 玩家复活')
  isDead.value = false
  clearRespawnTimer()
}

const startRespawnTimer = () => {
  // 清理之前可能存在的定时器
  clearRespawnTimer()
  
  const baseTime = currentPlayer.value?.ConsecutiveDeaths >= 2 ? 8 : 5
  respawnTime.value = baseTime
  respawnProgress.value = 0
  
  console.log('[Canvas] 开始复活倒计时:', {
    playerId: props.playerId,
    baseTime,
    isAlive: currentPlayer.value?.IsAlive
  })
  
  respawnTimer.value = setInterval(() => {
    respawnTime.value -= 0.1
    respawnProgress.value = (baseTime - respawnTime.value) / baseTime
    
    if (respawnTime.value <= 0) {
      clearRespawnTimer()
      requestRespawn()
    }
  }, 100)
}

const clearRespawnTimer = () => {
  if (respawnTimer.value) {
    console.log('[Canvas] 清理复活定时器:', props.playerId)
    clearInterval(respawnTimer.value)
    respawnTimer.value = null
  }
  respawnTime.value = 0
  respawnProgress.value = 0
}

const requestRespawn = async () => {
  if (!lineDrawingGameService.isConnected) return
  
  // 检查当前玩家是否真的已死亡
  if (currentPlayer.value?.IsAlive !== false) {
    console.log('[Canvas] 取消复活请求 - 玩家已存活:', {
      playerId: props.playerId,
      isAlive: currentPlayer.value?.IsAlive
    })
    clearRespawnTimer()
    return
  }
  
  console.log('[Canvas] 发送复活请求:', props.playerId)
  
  try {
    await lineDrawingGameService.respawn()
  } catch (error) {
    console.error('[Canvas] 复活失败:', error)
  }
}

// 地理位置判断
const isInOwnTerritory = (pos) => {
  if (!currentPlayer.value?.Territories) return false
  
  return currentPlayer.value.Territories.some(territory => 
    isPointInPolygon(pos, territory.Boundary)
  )
}

const isInEnemyTerritory = (pos) => {
  return players.value.some(player => {
    if (player.PlayerId === props.playerId || !player.Territories) return false
    return player.Territories.some(territory => isPointInPolygon(pos, territory.Boundary))
  })
}

const isInSafeZone = (pos) => {
  if (!currentPlayer.value?.SpawnPoint) return false
  
  const spawn = currentPlayer.value.SpawnPoint
  const distance = Math.sqrt(
    Math.pow(pos.x - spawn.x, 2) + Math.pow(pos.y - spawn.y, 2)
  )
  
  return distance <= GAME_CONFIG.safeZoneRadius
}

const isPointInPolygon = (point, polygon) => {
  if (!polygon || polygon.length < 3) return false
  
  let inside = false
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    if (((polygon[i].Y > point.y) !== (polygon[j].Y > point.y)) &&
        (point.x < (polygon[j].X - polygon[i].X) * (point.y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) + polygon[i].X)) {
      inside = !inside
    }
  }
  return inside
}

const isWithinMapBounds = (x, y) => {
  const distance = Math.sqrt(
    Math.pow(x - GAME_CONFIG.mapCenterX, 2) + 
    Math.pow(y - GAME_CONFIG.mapCenterY, 2)
  )
  return distance <= GAME_CONFIG.mapRadius - 10
}

// 渲染系统
const startRenderLoop = () => {
  const targetFPS = 60
  const targetFrameTime = 1000 / targetFPS
  
  const render = (timestamp) => {
    const deltaTime = timestamp - gameLoop.lastFrame
    
    // 限制帧率避免过度渲染
    if (deltaTime < targetFrameTime) {
      gameLoop.animationId = requestAnimationFrame(render)
      return
    }
    
    gameLoop.lastFrame = timestamp
    
    // 更新视角目标位置（跟随玩家）
    updateViewport()
    
    // 平滑视口移动
    viewport.x += (viewport.targetX - viewport.x) * viewport.smoothness
    viewport.y += (viewport.targetY - viewport.y) * viewport.smoothness
    
    // 更新UI状态（降低频率）
    if (timestamp % 3 < targetFrameTime) { // 每3帧更新一次UI状态
      updateUIState()
    }
    
    // 渲染游戏画面
    renderGame()
    
    gameLoop.animationId = requestAnimationFrame(render)
  }
  
  gameLoop.animationId = requestAnimationFrame(render)
}

const stopRenderLoop = () => {
  if (gameLoop.animationId) {
    cancelAnimationFrame(gameLoop.animationId)
    gameLoop.animationId = null
  }
}

const renderGame = () => {
  if (!ctx) return
  
  // 清空画布
  ctx.fillStyle = '#1a1a2e'
  ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value)
  
  // 渲染地图背景
  renderMapBackground()
  
  // 渲染安全区
  renderSafeZones()
  
  // 渲染领地
  renderTerritories()
  
  // 渲染道具
  renderPowerUps()
  
  // 渲染轨迹
  renderTrails()
  
  // 渲染玩家
  renderPlayers()
  
  // 渲染地图边界
  renderMapBoundary()
}

const renderMapBackground = () => {
  const centerX = GAME_CONFIG.mapCenterX - viewport.x
  const centerY = GAME_CONFIG.mapCenterY - viewport.y
  const radius = GAME_CONFIG.mapRadius
  
  // 径向渐变背景
  const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius)
  gradient.addColorStop(0, '#2a2a4e')
  gradient.addColorStop(0.7, '#1e1e3f')
  gradient.addColorStop(1, '#16213e')
  
  ctx.fillStyle = gradient
  ctx.beginPath()
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2)
  ctx.fill()
}

const renderMapBoundary = () => {
  const centerX = GAME_CONFIG.mapCenterX - viewport.x
  const centerY = GAME_CONFIG.mapCenterY - viewport.y
  const radius = GAME_CONFIG.mapRadius
  
  ctx.strokeStyle = '#ff6b6b'
  ctx.lineWidth = 3
  ctx.shadowBlur = 10
  ctx.shadowColor = '#ff6b6b'
  ctx.beginPath()
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2)
  ctx.stroke()
  ctx.shadowBlur = 0
}

const renderSafeZones = () => {
  // 为每个玩家渲染安全区（出生点周围的圆形区域）
  players.value.forEach(player => {
    const spawnPoint = player.spawnPoint || player.SpawnPoint
    if (!spawnPoint) return
    
    // 兼容不同的坐标字段格式
    const spawnX = spawnPoint.x || spawnPoint.X
    const spawnY = spawnPoint.y || spawnPoint.Y
    
    if (spawnX === undefined || spawnY === undefined) return
    
    const x = spawnX - viewport.x
    const y = spawnY - viewport.y
    const radius = GAME_CONFIG.safeZoneRadius
    
    // 渲染安全区背景（半透明圆形）
    ctx.globalAlpha = 0.2
    ctx.fillStyle = player.Color || '#4CAF50'
    ctx.beginPath()
    ctx.arc(x, y, radius, 0, Math.PI * 2)
    ctx.fill()
    
    // 渲染安全区边界（虚线圆圈）
    ctx.globalAlpha = 0.6
    ctx.strokeStyle = player.Color || '#4CAF50'
    ctx.lineWidth = 2
    ctx.setLineDash([8, 4]) // 虚线样式
    ctx.beginPath()
    ctx.arc(x, y, radius, 0, Math.PI * 2)
    ctx.stroke()
    ctx.setLineDash([]) // 重置为实线
    
    // 添加安全区标识
    ctx.globalAlpha = 0.8
    ctx.fillStyle = player.Color || '#4CAF50'
    ctx.font = '12px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('安全区', x, y + 4)
    
    ctx.globalAlpha = 1.0
  })
}

const renderTerritories = () => {
  players.value.forEach(player => {
    if (!player.Territories) return
    
    player.Territories.forEach(territory => {
      if (!territory.Boundary || territory.Boundary.length < 3) return
      
      // 填充领地
      ctx.fillStyle = player.Color || '#ffffff'
      ctx.globalAlpha = 0.3
      
      ctx.beginPath()
      territory.Boundary.forEach((point, index) => {
        const x = point.X - viewport.x
        const y = point.Y - viewport.y
        if (index === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      })
      ctx.closePath()
      ctx.fill()
      
      // 领地边界
      ctx.globalAlpha = 0.8
      ctx.strokeStyle = player.Color || '#ffffff'
      ctx.lineWidth = 2
      ctx.stroke()
    })
    
    ctx.globalAlpha = 1.0
  })
}

const renderPowerUps = () => {
  powerUps.value.forEach(powerUp => {
    // 兼容CamelCase字段
    const position = powerUp.position || powerUp.Position
    const powerUpType = powerUp.type || powerUp.Type
    
    if (!position) return
    
    const x = position.x - viewport.x
    const y = position.y - viewport.y
    
    if (x < -50 || x > canvasWidth.value + 50 || 
        y < -50 || y > canvasHeight.value + 50) return
    
    const color = getPowerUpColor(powerUpType)
    
    // 光环效果
    ctx.shadowBlur = 15
    ctx.shadowColor = color
    ctx.fillStyle = color
    ctx.globalAlpha = 0.4
    ctx.beginPath()
    ctx.arc(x, y, 18, 0, Math.PI * 2)
    ctx.fill()
    
    // 图标
    ctx.globalAlpha = 1.0
    ctx.fillStyle = color
    ctx.font = '24px Arial'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(getPowerUpIcon(powerUp.Type), x, y)
    
    ctx.shadowBlur = 0
  })
}

const renderTrails = () => {
  let trailsRendered = 0
  
  // 减少调试信息，只在轨迹变化时打印
  if (!renderTrails.lastCheck || Date.now() - renderTrails.lastCheck > 1000) {
    renderTrails.lastCheck = Date.now()
    console.log('[Canvas] 检查所有玩家轨迹状态:')
    players.value.forEach(player => {
      const isDrawing = player.IsDrawing || player.isDrawing
      const currentPath = player.CurrentPath || player.currentPath
      console.log(`  玩家 ${player.Username || player.username}: IsDrawing=${isDrawing}, PathLength=${currentPath ? currentPath.length : 0}`)
    })
  }
  
  // 渲染其他玩家的轨迹
  players.value.forEach(player => {
    const isDrawing = player.IsDrawing || player.isDrawing
    const currentPath = player.CurrentPath || player.currentPath
    
    if (!isDrawing || !currentPath || currentPath.length < 2) return
    trailsRendered++
    
    // 只在轨迹长度变化时打印
    const playerId = player.PlayerId || player.playerId
    const pathLength = currentPath.length
    if (!renderTrails.lastPathLengths) renderTrails.lastPathLengths = {}
    if (renderTrails.lastPathLengths[playerId] !== pathLength) {
      console.log(`[Canvas] 玩家 ${player.Username || player.username} 轨迹更新: ${pathLength} 个点`)
      renderTrails.lastPathLengths[playerId] = pathLength
    }
    
    ctx.strokeStyle = player.Color || '#ffffff'
    ctx.lineWidth = player.PlayerId === props.playerId ? 4 : 3
    ctx.lineCap = 'round'
    ctx.lineJoin = 'round'
    
    ctx.beginPath()
    currentPath.forEach((point, index) => {
      const x = point.x - viewport.x
      const y = point.y - viewport.y
      if (index === 0) {
        ctx.moveTo(x, y)
      } else {
        ctx.lineTo(x, y)
      }
    })
    ctx.stroke()
  })
  
  // 渲染本地预览轨迹
  if (drawing.isActive && drawing.localTrail.length >= 1) {
    trailsRendered++
    console.log('[Canvas] 渲染本地轨迹:', drawing.localTrail.length, '个点')
    
    ctx.strokeStyle = currentPlayer.value?.Color || '#ffffff'
    ctx.lineWidth = 4
    ctx.globalAlpha = 0.8
    ctx.lineCap = 'round'
    ctx.lineJoin = 'round'
    
    if (drawing.localTrail.length === 1) {
      // 单个点渲染为圆点
      const point = drawing.localTrail[0]
      const x = point.x - viewport.x
      const y = point.y - viewport.y
      
      ctx.beginPath()
      ctx.arc(x, y, 2, 0, Math.PI * 2)
      ctx.fillStyle = currentPlayer.value?.Color || '#ffffff'
      ctx.fill()
    } else {
      // 多个点渲染为线条
      ctx.beginPath()
      drawing.localTrail.forEach((point, index) => {
        const x = point.x - viewport.x
        const y = point.y - viewport.y
        if (index === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      })
      ctx.stroke()
    }
    
    ctx.globalAlpha = 1.0
  }
  
  if (trailsRendered === 0 && drawing.isActive) {
    console.log('[Canvas] 应该渲染轨迹但没有渲染:', {
      isActive: drawing.isActive,
      localTrailLength: drawing.localTrail.length,
      playersWithTrails: players.value.filter(p => p.IsDrawing && p.CurrentPath).length
    })
  }
}

const renderPlayers = () => {
  players.value.forEach(player => {
    // 使用映射后的字段（在updateGameState中已处理）
    if (!player.IsAlive || !player.CurrentPosition) return
    
    const x = player.CurrentPosition.x - viewport.x
    const y = player.CurrentPosition.y - viewport.y
    
    if (x < -50 || x > canvasWidth.value + 50 || 
        y < -50 || y > canvasHeight.value + 50) return
    
    const isMe = player.PlayerId === props.playerId
    let radius = isMe ? 14 : 12
    
    // 道具效果
    if (player.CurrentPowerUp === 'Lightning') radius += 2
    
    // 无敌期闪烁
    let alpha = 1.0
    if (player.InvincibilityEndTime && new Date(player.InvincibilityEndTime) > new Date()) {
      alpha = (Math.sin(Date.now() / 100) + 1) / 2 * 0.6 + 0.4
    }
    
    ctx.globalAlpha = alpha
    
    // 玩家球体
    ctx.fillStyle = player.Color || '#ffffff'
    ctx.beginPath()
    ctx.arc(x, y, radius, 0, Math.PI * 2)
    ctx.fill()
    
    // 边框
    ctx.strokeStyle = isMe ? '#ffffff' : '#333'
    ctx.lineWidth = 2
    ctx.stroke()
    
    // 特殊效果
    if (player.HasShield) {
      ctx.strokeStyle = '#FFD700'
      ctx.lineWidth = 3
      ctx.beginPath()
      ctx.arc(x, y, radius + 6, 0, Math.PI * 2)
      ctx.stroke()
    }
    
    if (player.IsGhost) {
      ctx.globalAlpha = alpha * 0.5
      ctx.strokeStyle = '#9C27B0'
      ctx.lineWidth = 2
      ctx.setLineDash([5, 5])
      ctx.beginPath()
      ctx.arc(x, y, radius + 8, 0, Math.PI * 2)
      ctx.stroke()
      ctx.setLineDash([])
    }
    
    // 玩家名称
    ctx.globalAlpha = 1.0
    ctx.fillStyle = '#ffffff'
    ctx.font = '14px Arial'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'top'
    ctx.fillText(player.Username, x, y + radius + 8)
  })
}

// 工具函数
const getPowerUpColor = (type) => {
  const colors = {
    Lightning: '#4FC3F7',
    Shield: '#FFD700',
    Bomb: '#F44336',
    Ghost: '#9C27B0'
  }
  return colors[type] || '#ffffff'
}

const getPowerUpIcon = (type) => {
  const icons = {
    Lightning: '⚡',
    Shield: '🛡️',
    Bomb: '💣',
    Ghost: '👻'
  }
  return icons[type] || '?'
}

const getPowerUpName = (type) => {
  const names = {
    Lightning: '闪电',
    Shield: '护盾',
    Bomb: '炸弹',
    Ghost: '幽灵'
  }
  return names[type] || '未知道具'
}

// 画布初始化
const initCanvas = () => {
  ctx = gameCanvas.value.getContext('2d')
  ctx.imageSmoothingEnabled = false
  gameCanvas.value.focus()
  
  console.log('[Canvas] 初始化完成')
}

const resizeCanvas = () => {
  const container = gameCanvas.value?.parentElement
  if (!container) return
  
  const rect = container.getBoundingClientRect()
  const aspectRatio = 3 / 2
  
  let width = rect.width
  let height = width / aspectRatio
  
  if (height > rect.height) {
    height = rect.height
    width = height * aspectRatio
  }
  
  canvasWidth.value = Math.max(800, Math.floor(width))
  canvasHeight.value = Math.max(533, Math.floor(height))
}

// 事件监听器
const setupEventListeners = () => {
  window.addEventListener('blur', handleBlur)
  window.addEventListener('resize', resizeCanvas)
}

const removeEventListeners = () => {
  window.removeEventListener('blur', handleBlur)
  window.removeEventListener('resize', resizeCanvas)
}

// 响应式数据监听
watch(() => props.gameState, (newState) => {
  updateGameState(newState)
}, { deep: true, immediate: true })

watch(() => props.playerId, () => {
  updateCurrentPlayer()
}, { immediate: true })

// 生命周期钩子
onMounted(() => {
  console.log('[Canvas] 组件加载')
  
  initCanvas()
  resizeCanvas()
  startRenderLoop()
  setupEventListeners()
  
  nextTick(() => {
    gameCanvas.value?.focus()
  })
})

onUnmounted(() => {
  console.log('[Canvas] 组件卸载')
  
  stopRenderLoop()
  stopMoving()
  clearRespawnTimer()
  removeEventListeners()
})

// 处理移动被拒绝事件
const handleMoveRejected = (data) => {
  console.log('[Canvas] 处理移动被拒绝:', data)
  
  const errors = data?.Errors || data?.errors || []
  const isDeathRelated = errors.some(error => 
    error.includes('死亡') || error.includes('自撞')
  )
  
  // 注释掉死亡相关的处理，专注于移动逻辑调试
  // if (isDeathRelated) {
  //   console.log('[Canvas] 检测到死亡相关的移动被拒绝，立即停止移动')
  //   // 立即停止所有移动操作
  //   stopMoving()
  //   // 设置死亡状态
  //   isDead.value = true
  //   // 如果有死亡原因，更新显示
  //   if (errors.length > 0) {
  //     deathReason.value = errors[0]
  //   }
  // } else {
    // 对于所有类型的移动被拒绝，都停止移动操作
    console.log('[Canvas] 移动被拒绝，停止移动操作:', errors.join(', '))
    stopMoving()
  // }
}

// 导出方法给父组件调用
defineExpose({
  handleMoveRejected
})
</script>

<style scoped>
.game-canvas-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #0f0f23 0%, #1a1a2e 50%, #16213e 100%);
  overflow: hidden;
}

.game-canvas {
  display: block;
  border: 2px solid rgba(255, 107, 107, 0.4);
  border-radius: 12px;
  box-shadow: 0 0 30px rgba(255, 107, 107, 0.3);
  cursor: crosshair;
  outline: none;
  background: transparent;
}

.game-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 10;
}

.path-warning {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 152, 0, 0.9);
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
  animation: pulse 1s ease-in-out infinite alternate;
  backdrop-filter: blur(10px);
}

.threat-warning {
  position: absolute;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(244, 67, 54, 0.9);
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
  animation: blink 0.6s ease-in-out infinite alternate;
  backdrop-filter: blur(10px);
}

.progress-bar {
  width: 100px;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: white;
  transition: width 0.3s ease;
  border-radius: 2px;
}

.powerup-status {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 15px 20px;
  border-radius: 8px;
  text-align: center;
  backdrop-filter: blur(10px);
  min-width: 120px;
}

.powerup-icon {
  font-size: 28px;
  display: block;
  margin-bottom: 5px;
}

.powerup-name {
  font-size: 14px;
  color: #ccc;
  margin-bottom: 5px;
}

.powerup-time {
  font-size: 16px;
  font-weight: bold;
  color: #4CAF50;
}

.controls-hint {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 10px 15px;
  border-radius: 6px;
  font-size: 12px;
  line-height: 1.4;
  backdrop-filter: blur(5px);
}

.death-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  backdrop-filter: blur(5px);
}

.death-modal {
  background: linear-gradient(145deg, #d32f2f, #b71c1c);
  color: white;
  padding: 40px;
  border-radius: 16px;
  text-align: center;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
  max-width: 350px;
}

.death-icon {
  font-size: 64px;
  margin-bottom: 20px;
  animation: bounce 2s ease-in-out infinite;
}

.death-title {
  font-size: 28px;
  font-weight: bold;
  margin: 0 0 15px 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.death-reason {
  font-size: 16px;
  color: #ffcdd2;
  margin: 0 0 30px 0;
  opacity: 0.9;
}

.respawn-countdown {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.countdown-circle {
  position: relative;
  display: inline-block;
}

.countdown-number {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.countdown-label {
  font-size: 14px;
  color: #ffcdd2;
  opacity: 0.8;
}

@keyframes pulse {
  from { background: rgba(255, 152, 0, 0.7); }
  to { background: rgba(255, 152, 0, 1); }
}

@keyframes blink {
  from { background: rgba(244, 67, 54, 0.7); }
  to { background: rgba(244, 67, 54, 1); }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-10px); }
  60% { transform: translateY(-5px); }
}

@media (max-width: 768px) {
  .path-warning,
  .threat-warning {
    left: 10px;
    right: 10px;
    transform: none;
  }
  
  .powerup-status {
    right: 10px;
    padding: 10px 15px;
  }
  
  .controls-hint {
    left: 10px;
    right: 10px;
    text-align: center;
  }
  
  .death-modal {
    margin: 20px;
    padding: 30px;
  }
}
</style>
